//
//  BMBaseModel+BMExtensions.m
//  砼车Demo
//
//  Created by apple on 16/1/7.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "BMBaseModel+BMExtensions.h"
#import "BMHttpTool.h"


@implementation BMBaseModel (BMExtensions)

+ (BMResponse *)responseWith:(id)responseObj contentKey: (NSString *)contentKey
{
    BMResponse *response = [BMResponse mj_objectWithKeyValues:responseObj];
    id result = responseObj[@"data"];
    response.rawResult = result;
    
    if (result &&![result isKindOfClass:[NSNull class]] && contentKey && ![result isKindOfClass:[NSDictionary class]]) {
        NSDictionary *pageDict = result[@"page"];
        if (pageDict) {
            response.page = [BMPage mj_objectWithKeyValues:pageDict];
        }
        result = result[contentKey];
    }
    
    if (result && ![result isKindOfClass:[NSNull class]]) {
        response.emptyResult = NO;
        if ([result isKindOfClass:[NSArray class]]) {
            response.result = [self mj_objectArrayWithKeyValuesArray:result];
        }else if([result isKindOfClass:[NSDictionary class]]){
            response.result = [self mj_objectWithKeyValues:result];
        }
    }else{
        response.emptyResult = YES;
    }
    return  response;
}

+(void)getWithRequest:(BMRequest *)request finish:(finishBlock)finish{
    [[BMHttpTool sharedInstance].manager GET:[kInterfacePath stringByAppendingPathComponent:request.path] parameters:request.params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        BMResponse *response = [self responseWith:responseObject contentKey:request.contentKey];
        finish(response,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finish(nil,error);
    }];
}

+ (void)postWithRequest:(BMRequest *)request finish:(finishBlock)finish{
    [[BMHttpTool sharedInstance].manager POST:[kInterfacePath stringByAppendingPathComponent:request.path] parameters:request.params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        BMResponse *response = [self responseWith:responseObject contentKey:request.contentKey];
        finish(response,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finish(nil,error);
    }];
}

+ (BMResponse *)getCacheWith:(BMRequest *)request{
    NSString *cachePath = [self encodePath:request.path];
    BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:cachePath];
    if (!exists) return nil;
    
    id cacheFile = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];
    
    if (!cacheFile) return nil;
    
    BMResponse *response = [BMResponse new];
    response.status = 1;
    response.emptyResult = NO;
    response.fromCache = YES;
    
    if ([cacheFile isKindOfClass:[NSArray class]]) {
        response.rawResult = cacheFile;
        response.result = [self mj_objectArrayWithFile:cacheFile];
        return response;
    }else if([cacheFile isKindOfClass:[NSDictionary class]]){
        response.rawResult = cacheFile;
        response.result = [self mj_objectWithKeyValues:cacheFile];
        return response;
    }
    return nil;
}

+ (void)cacheResponse:(BMResponse *)response withRequest:(BMRequest *)request{
    
    if (!response || response.status!= 1 || response.isEmptyResult || response.fromCache ) {
        return;
    }
    
    NSString *cachaPath = [self encodePath:request.path];
    if (cachaPath) {
        [self checkDirectory];
        [NSKeyedArchiver archiveRootObject:response.rawResult toFile:cachaPath];
    }
    
}

+ (void)checkDirectory{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingPathComponent:@"xbrcCache"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir;
    if (![fileManager fileExistsAtPath:path isDirectory:&isDir]) {
        [self createBaseDirectoryAtPath:path];
    }else{
        if (!isDir) {
            NSError *error = nil;
            [fileManager removeItemAtPath:path error:&error];
            [self createBaseDirectoryAtPath:path];
        }
    }
    
}

+ (void)createBaseDirectoryAtPath:(NSString *)path{
    __autoreleasing NSError *error = nil;
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
    if (error) {
        BMLog(@"create cache directory failed, error = %@", error);
    }
}

+ (NSString *)encodePath:(NSString *)path{
    NSString *cachePath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    cachePath = [cachePath stringByAppendingPathComponent:@"xbrcCache"];
    return [cachePath stringByAppendingPathComponent:[path stringByReplacingOccurrencesOfString:@"/" withString:@"."]];
}














@end
